package com.bawei.module_mall.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bawei.module_mall.R
import com.bawei.module_mall.model.SearchGoodsModelItem
import com.bumptech.glide.Glide

/**
 *@author：lxy
 *@decription:
 *@time：2025/7/7
 */
class GoodsAdapter(
    private val onItemClick: (SearchGoodsModelItem) -> Unit,
    private val showAddButton: Boolean = false, // 新增参数
    private val onAddToShowcase: ((SearchGoodsModelItem) -> Unit)? = null // 新增回调
) : RecyclerView.Adapter<GoodsAdapter.GoodsViewHolder>() {

    private var list: List<SearchGoodsModelItem> = emptyList()

    inner class GoodsViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val ivPic: ImageView = view.findViewById(R.id.ivPic)
        val tvTitle: TextView = view.findViewById(R.id.tvTitle)
        val tvPrice: TextView = view.findViewById(R.id.tvPrice)
        val tvSold: TextView = view.findViewById(R.id.tvSold)
        val btnAddToShowcase: View = view.findViewById(R.id.btnAddToShowcase) // 新增
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): GoodsViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_goods_card, parent, false)
        return GoodsViewHolder(view)
    }

    override fun onBindViewHolder(holder: GoodsViewHolder, position: Int) {
        val item = list[position]
        Glide.with(holder.itemView).load(item.mainImgUrl).into(holder.ivPic)
        holder.tvTitle.text = item.title
        holder.tvPrice.text = "￥${item.marketPriceFee / 100.0}"
        holder.tvSold.text = "已售${item.soldNum}"

        holder.itemView.setOnClickListener { onItemClick(item) }

        // 控制按钮显示
        holder.btnAddToShowcase.visibility = if (showAddButton) View.VISIBLE else View.GONE

        holder.btnAddToShowcase.setOnClickListener {
            onAddToShowcase?.invoke(item)
        }
    }

    override fun getItemCount() = list.size

    fun submitList(newList: List<SearchGoodsModelItem>) {
        list = newList
        notifyDataSetChanged()
    }

    fun getCurrentList(): List<SearchGoodsModelItem> {
        return list
    }
}